package com.wdy.ssafe;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import org.springframework.stereotype.Component;

@Component
public class TokenManager {

  private static final long expire = 24 * 60 * 60 * 1000;
  private static final String tokenSignKey = "123456";

  // 根据用户名生成 token
  public String createToken(String username){
    return Jwts.builder()
        .setSubject(username).setExpiration(new Date(System.currentTimeMillis() + expire))
        .signWith(SignatureAlgorithm.HS512, tokenSignKey)
        .compressWith(CompressionCodecs.GZIP)
        .compact();
  }

  // 根据 token 字符串得到用户信息
  public String parseToken(String token) {
    return Jwts.parser().setSigningKey(tokenSignKey)
        .parseClaimsJws(token)
        .getBody()
        .getSubject();
  }
}